<!--  -->
<template>
  <div>
    <div class="container" style="text-align: left;">
      <validate-form @form-submit="onFormSubmit">
        <div class="mb-3">
          <span>邮箱地址</span>
          <validate-input :rules="emailRules" v-model="emailVal" placeholder="请输入邮箱地址" type="email" ref="inputRef1">
          </validate-input>
        </div>
        <div class="mb-3">
          <span>密码</span>
          <validate-input :rules="passwordRules" v-model="passwordVal" type="password" placeholder="请输入密码"
            ref="inputRef3">
          </validate-input>
        </div>
        <template v-slot:submit>
          <span class="btn btn-danger">登录</span>
          <span class="btn btn-danger" style="margin-left: 10px;" @click="this.$router.push('/register')">注册</span>
        </template>
      </validate-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import 'bootstrap/dist/css/bootstrap.min.css'
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateInput, { RulesProp } from '@/components/ValidateInput.vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

export default defineComponent({
  name: "LoginPage",
  components: { ValidateInput, ValidateForm },
  setup() {
    const store = useStore()
    const router = useRouter()
    const inputRef1 = ref<any>()
    const inputRef2 = ref<any>()
    const inputRef3 = ref<any>()
    const emailVal = ref('123@test.com')
    const usernameVal = ref('mathieu')
    const passwordVal = ref('lzh2234567')
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' }
    ]
    const usernameRules: RulesProp = [
      { type: 'required', message: '用户名不能为空' },
      { type: 'username_min', message: '用户名不能少于3个字' },
      { type: 'username_max', message: '用户名不能多于10个字' }
    ]
    const passwordRules: RulesProp = [
      { type: 'required', message: '密码不能为空' },
      { type: 'password_min', message: '密码不能少于6个字' },
      { type: 'password_max', message: '密码不能多于15个字' }
    ]
    const onFormSubmit = async (result: boolean) => {
      if (result) {
        const params = { email: emailVal.value, password: passwordVal.value }
        try {
          await store.dispatch('login', params)

          await store.commit('TOKEN')
          await store.dispatch('getUserInfo')
          router.push({ name: 'home' })
        } catch (error) {
          // alert(error)
        }
      }
      // console.log('result', inputRef1.value.validateInput() && inputRef2.value.validateInput() && inputRef3.value.validateInput())
    }
    return {
      emailRules,
      usernameRules,
      passwordRules,
      emailVal,
      usernameVal,
      passwordVal,
      onFormSubmit,
      inputRef1,
      inputRef2,
      inputRef3,
    }
  }
})
</script>

<style  scoped lang='less'>

</style>
